# -*- encoding: utf-8 -*-
from odoo import models, fields, api
from .. import public


class SubaccountCategory(models.Model):
    _name = 'subaccount.category'
    # _inherit = ['mail.thread']
    _description = u'辅助核算类别设定'

    code = fields.Char(u'编码')
    name = fields.Char(u'辅助核算类别', translate=False)
    note = fields.Char(u'备注', )
    active = fields.Boolean(u'启用', default=True)
    sub_account_ids = fields.One2many('res.partner', 'subaccount_category_id', u'辅助核算')
    is_system_created = fields.Boolean(u'系统预设', default=False, readonly=True)

    partner_id = fields.Many2one('res.partner', '按供应商过滤')
    company_id = fields.Many2one('res.company', string=u'公司', default=lambda self: self.env.company)

    _sql_constraints = [('code_unique', 'unique (code)', u'辅助核算类别编码不能重复!'),
                        ('name_unique', 'unique (name)', u'辅助核算类别名称不能重复!'), ]

    # @api.model
    def create(self, values):
        if 'code' in values:
            if values['code']:
                public.check_unique(self, ['code'], values, u'编码')
        if 'name' in values:
            if values['name']:
                public.check_unique(self, ['name'], values, u'辅助核算类别')
        res_id = super(SubaccountCategory, self).create(values)
        return res_id

    def action_sync_hr_employee(self):
        self.ensure_one()
        emps = self.env['hr.employee'].search([('active', '!=', False)])
        for x in emps:
            item = dict(code=x.code,
                        name=x.name,
                        subaccount_category_id=self.id,
                        active=True,
                        customer_rank=0,
                        supplier_rank=0,
                        employee=True,
                        )
            self.create_or_write(x, item)

    def create_or_write(self, x, item):
        res_partner_id = self.env['res.partner'].search(
            [('code', '=', item.get('code')), ('name', '=', item.get('name'))])
        if res_partner_id:
            res_partner_id.write(item)
            res_partner_id.customer_rank = False
            x.partner_id = res_partner_id.id
        else:
            partner_id = self.env['res.partner'].create(item)
            partner_id.customer_rank = False
            x.partner_id = partner_id.id

    def action_sync_hr_department(self):
        self.ensure_one()

        depts = self.env['hr.department'].search([('partner_id', '=', False), ('active', '!=', False)])
        for x in depts:
            item = dict(code=x.code,
                        name=x.name,
                        subaccount_category_id=self.id,
                        active=True,
                        customer_rank=0,
                        supplier_rank=0,
                        employee=False,
                        # state='approve',
                        )
            self.create_or_write(x, item)

    def action_sync_cash_flow(self):
        self.ensure_one()
        report = self.env['account.report.format.designer'].search([('report_type', '=', 'cash')], limit=1)
        for x in report.line_ids.filtered(lambda x: x.partner_id and x.llc > 0):
            item = dict(code='cash_%s' % (
                str(x.sequence).zfill(len(str(x.sequence)) if len(str(x.sequence)) >= 2 else len(str(x.sequence)) + 1)),
                        name=x.name,
                        subaccount_category_id=self.id,
                        customer_rank=0,
                        supplier_rank=0,
                        employee=False,
                        active=True,
                        )
            self.create_or_write(x, item)

        for x in report.line_ids.filtered(lambda x: not x.partner_id and x.llc > 0):
            item = dict(code='cash_%s' % (
                str(x.sequence).zfill(len(str(x.sequence)) if len(str(x.sequence)) >= 2 else len(str(x.sequence)) + 1)),
                        name=x.name,
                        subaccount_category_id=self.id,
                        customer_rank=0,
                        supplier_rank=0,
                        employee=False,
                        active=True,
                        )
            self.create_or_write(x, item)
            # self._cr.commit()

    def action_sync_bank(self):
        self.ensure_one()
        if self.partner_id:
            bank_ids = self.env['res.partner.bank'].search([('partner_id', '=', self.partner_id.id),
                                                            ('acc_number', '!=', False), ('bank_id', '!=', False)])
        else:
            bank_ids = self.env['res.partner.bank'].search([('acc_number', '!=', False), ('bank_id', '!=', False)])
        for x in bank_ids:
            item = dict(code=x.acc_number,
                        name=x.acc_number,
                        subaccount_category_id=self.id,
                        active=True,
                        customer_rank=0,
                        supplier_rank=0,
                        employee=False,
                        )
            self.create_or_write(x, item)

    def write(self, vals):
        if 'code' in vals:
            public.check_unique(self, ['code'], vals, u'编码')
        if 'name' in vals:
            public.check_unique(self, ['name'], vals, u'辅助核算类别')
        return super(SubaccountCategory, self).write(vals)





# class AccountJournal(models.Model):
#     _name = "cw.accjournal"
#     _inherit = "cncw.account.journal"
#     _description = u'日记账辅助核算'
#
#     @api.model
#     def _prepare_liquidity_account(self, name, company, currency_id, type):
#         res = super(AccountJournal, self)._prepare_liquidity_account(name, company, currency_id, type)
#         subaccount_category_id = self.env['subaccount.category'].search([('code', '=', 'cash_flow')], limit=1)
#         if type in ('bank', 'cash'):
#             res.update(dict(sub_account_type='has',
#                             name=u'银行存款' if type == 'bank' else u'库存现金',
#                             subaccount_category_id=subaccount_category_id and subaccount_category_id.id or False))
#         return res


# class AccountChartTemplate(models.Model):
#     _inherit = "cncw.chart.template"
#
#     def generate_account(self, tax_template_ref, acc_template_ref, code_digits, company):
#         """ This method for generating accounts from templates.
#
#             :param tax_template_ref: Taxes templates reference for write taxes_id in cncw_account.
#             :param acc_template_ref: dictionary with the mappping between the account templates and the real accounts.
#             :param code_digits: number of digits got from wizard.multi.charts.accounts, this is use for account code.
#             :param company_id: company_id selected from wizard.multi.charts.accounts.
#             :returns: return acc_template_ref for reference purpose.
#             :rtype: dict
#         """
#         self.ensure_one()
#         account_tmpl_obj = self.env['cncw.account.template']
#         acc_template = account_tmpl_obj.search([('nocreate', '!=', True), ('chart_template_id', '=', self.id)],
#                                                order='id')
#         for account_template in acc_template:
#             tax_ids = []
#             for tax in account_template.tax_ids:
#                 tax_ids.append(tax_template_ref[tax.id])
#
#             # code_main = account_template.code and len(account_template.code) or 0
#             # code_acc = account_template.code or ''
#             # if code_main > 0 and code_main <= code_digits:
#             #     code_acc = str(code_acc) + (str('0'*(code_digits-code_main)))
#             # parent_id=self.env['cncw.account'].search([('code','=',account_template.parent_id.code),
#             #                                               ('company_id','=',self.env.user.company_id.id)],limit=1)
#             vals = {
#                 'name': account_template.name,
#                 'currency_id': account_template.currency_id and account_template.currency_id.id or False,
#                 'code': account_template.code,
#                 'user_type_id': account_template.user_type_id and account_template.user_type_id.id or False,
#                 'reconcile': account_template.reconcile,
#                 'note': account_template.note,
#                 'tax_ids': [(6, 0, tax_ids)],
#                 'company_id': company.id,
#                 'tag_ids': [(6, 0, [t.id for t in account_template.tag_ids])],
#                 'parent_id': acc_template_ref.get(account_template.parent_id and account_template.parent_id.id or 0,
#                                                   False),
#                 'subaccount_category_id': account_template.user_type_id and account_template.subaccount_category_id.id or False,
#                 'sub_account_type': account_template.sub_account_type,
#                 'dc_type': account_template.dc_type,
#                 'active': account_template.active,
#                 'account_category': account_template.account_category,
#                 'ap_ar_type': account_template.ap_ar_type,
#             }
#             new_account = self.env['cncw.account'].create(vals)
#             # try:
#             #     new_account = self.env['cncw.account'].create(vals)
#             # except e:
#             #     pass
#             acc_template_ref[account_template.id] = new_account.id
#         return acc_template_ref


# class AccountAccountTemplate(models.Model):
#     _name = "cncw.account.template"
#
#     parent_id = fields.Many2one('cncw.account.template', u'上级科目', ondelete='cascade', domain=[('type', '=', 'view')])
#     children_ids = fields.One2many('cncw.account.template', 'parent_id', u'明细科目')
#     user_type_id = fields.Many2one('cncw.account.type', string='Type', required=False, oldname="user_type", )
#     sub_account_type = fields.Selection(public.SUB_ACCOUNT_TYPE, u'会科属性', required=True, default='none')
#     subaccount_category_id = fields.Many2one('subaccount.category', u'辅助核算类别', required=False,
#                                              ondelete="restrict")
#     dc_type = fields.Selection(public.DC_TYPE, u'借贷', default='D')
#     active = fields.Boolean(u'启用', default=True)
#     parent_left = fields.Integer(u'Parent Left', default=0)
#     parent_right = fields.Integer(u'Parent Right', default=0)
#     account_category = fields.Selection([('1', u'资产类'),
#                                          ('2', u'负债类'),
#                                          ('3', u'共同类'),
#                                          ('4', u'所有者权益类'),
#                                          ('5', u'成本类'),
#                                          ('6', u'费用类'),
#                                          ('7', u'收入类'),
#                                          ], u'科目大类', default='1')
#
#     ap_ar_type = fields.Selection([('10', u'预付帐款'),
#                                    ('11', u'应付帐款'),
#                                    ('12', u'应付费用'),
#                                    ('13', u'其它应付'),
#                                    ('20', u'预收帐款'),
#                                    ('21', u'应收帐款'),
#
#                                    ('23', u'其它应收'), ], u'应付应收科目类别', help=u'用于ap ar 月结时金额规类汇总')


# class AccountAccountType(models.Model):
#     _name = "cncw.account.type"
#
#     type = fields.Selection([
#         ('other', 'Regular'),
#         ('receivable', 'Receivable'),
#         ('payable', 'Payable'),
#         ('liquidity', 'Liquidity'),
#     ], required=True, default='other',
#         help="The 'Internal Type' is used for features available on " \
#              "different types of accounts: liquidity type is for cash or bank accounts" \
#              ", payable/receivable is for vendor/customer accounts.")
#
#     @api.model
#     def create(self, values):
#         if 'name' in values:
#             if values['name']:
#                 public.check_unique(self, ['name'], values, u'科目类型')
#         res_id = super(AccountAccountType, self).create(values)
#         return res_id
#
#     def write(self, vals, ):
#         if 'name' in vals:
#             public.check_unique(self, ['name'], vals, u'科目类型')
#         res = super(AccountAccountType, self).write(vals)
#         return res

#
# class AccountAccount(models.Model):
#     _name = "cncw.account"
#     _order = "parent_left"
#     _parent_order = "code"
#     _parent_store = True
#     _description = u"会计科目设定"
#     _rec_name = 'code'
#
#     @api.depends('code', 'complete_name')
#     def name_get(self):
#         res = []
#         for record in self:
#             name = '%s' % (record.complete_name)
#             # name=record.code
#             res.append((record['id'], name))
#         return res
#
#     @api.model
#     def name_search(self, name, args=None, operator='ilike', limit=100):
#         args = args or []
#         recs = self.browse()
#         if name:
#             recs = self.search(
#                 ['|', '|', '|', ('name', operator, name), '&', ('code', 'like', name), ('code', '>=', name),
#                  ('short_code', operator, name), ('complete_name', operator, name)] + args,
#                 limit=limit)
#         if not recs:
#             recs = self.search([('name', operator, name)] + args, limit=limit)
#         return recs.name_get()
#
#     @api.model
#     def get_sub_account_ids(self, account_id=False):
#         """
#         由会科取其 可用 辅助核算
#         :param self:
#         :param account_id:
#         :return:
#         """
#         subaccounts = self.env['res.partner'].browse([])
#         # 增加判断是否有多辅助核算的数据，没有的话沿用原来的逻辑
#         if account_id and account_id.subaccount_category_ids:
#             for subaccount_category_id in account_id.subaccount_category_ids:
#                 if subaccount_category_id.code == 'customer':
#                     subaccounts = self.env['res.partner'].search([('customer_rank', '>', 0)])
#                 elif subaccount_category_id.code == 'supplier':
#                     subaccounts = self.env['res.partner'].search([('supplier_rank', '>', 0)])
#                 else:
#                     for x in subaccount_category_id.sub_account_ids:
#                         subaccounts |= x
#         elif account_id and account_id.subaccount_category_id:
#             if account_id.subaccount_category_id.code == 'customer':
#                 subaccounts = self.env['res.partner'].search([('customer_rank', '>', 0)])
#             elif account_id.subaccount_category_id.code == 'supplier':
#                 subaccounts = self.env['res.partner'].search([('supplier_rank', '>', 0)])
#             else:
#                 for x in account_id.subaccount_category_id.sub_account_ids:
#                     subaccounts |= x
#         return subaccounts
#
#     def update_level(self):
#         objs = self.env['cncw.account'].search([('active', '=', True)])
#         for obj in objs:
#             obj._get_level()
#
#     @api.depends('parent_id')
#     def _get_level(self):
#         level = 1
#         parent = self.parent_id
#         while parent:
#             level += 1
#             parent = parent.parent_id
#         self.level = level
#
#     @api.depends('parent_id', 'code', 'name')
#     def _compute_complete_code(self):
#         for record in self:
#             name = ""
#             code = ""
#             if record.parent_id:
#                 # code = (self.parent_id and self.parent_id.complete_code or '')
#                 name = (record.parent_id and record.parent_id.complete_name or '')
#             # code += (self.code and self.code or '')
#             name += (record.name and record.name or '')
#             record.complete_name = name
#
#     @api.depends('children_ids', 'parent_id')
#     def complete_has_children(self):
#         for record in self:
#             if record.parent_id and not record.parent_id.has_children:
#                 record.parent_id.has_children = True
#             if len(record.children_ids) > 0:
#                 record.has_children = True
#             else:
#                 record.has_children = False
#     code = fields.Char(u'科目编码', required=True)
#     has_children = fields.Boolean(u'有子阶', default=False, compute="complete_has_children")
#     name = fields.Char(u'科目名称', required=True)
#     complete_name = fields.Char(compute='_compute_complete_code', store=True, string=u'全称')
#     parent_id = fields.Many2one('cncw.account', u'上级科目', ondelete='cascade', domain=[('type', '=', 'view')])
#     children_ids = fields.One2many('cncw.account', 'parent_id', u'明细科目')
#     user_type_id = fields.Many2one('cncw.account.type', string='Type', required=False, oldname="user_type", )
#     sub_account_type = fields.Selection(public.SUB_ACCOUNT_TYPE, u'会科属性', required=True, default='none')
#     subaccount_category_id = fields.Many2one('subaccount.category', u'辅助核算类别', required=False,
#                                              ondelete="restrict")
#     subaccount_category_ids = fields.Many2many('subaccount.category', string=u'辅助核算类别')
#     dc_type = fields.Selection(public.DC_TYPE, u'借贷', default='D')
#     dc_type_int = fields.Integer(u'借贷integer值', help=u'用于计算', compute='compute_dc_type', store=True)
#     active = fields.Boolean(u'启用', default=True)
#     parent_left = fields.Integer(u'Parent Left', default=0)
#     parent_right = fields.Integer(u'Parent Right', default=0)
#     parent_path = fields.Char(index=True)
#     level = fields.Integer(u'阶层', compute='_get_level', store=True, default=1)
#     account_category = fields.Selection([('1', u'资产类'),
#                                          ('2', u'负债类'),
#                                          ('3', u'共同类'),
#                                          ('4', u'所有者权益类'),
#                                          ('5', u'成本类'),
#                                          ('6', u'费用类'),
#                                          ('7', u'收入类'),
#                                          ], u'科目大类', default='1')
#
#     ap_ar_type = fields.Selection([('10', u'预付帐款'),
#                                    ('11', u'应付帐款'),
#                                    ('12', u'应付费用'),
#                                    ('13', u'其它应付'),
#                                    ('20', u'预收帐款'),
#                                    ('21', u'应收帐款'),
#
#                                    ('23', u'其它应收'), ], u'应付应收科目类别', help=u'用于ap ar 月结时金额规类汇总')
#     currency_id = fields.Many2one(
#         default=lambda self: self.env['res.company']._company_default_get('cncw.account').currency_id)
#     short_code = fields.Char(u'简码')
#
#     def get_subaccount_category_ids(self):
#         res = self.env['subaccount.category']
#         for record in self:
#             if record.sub_account_type == 'has':
#                 res |= record.subaccount_category_ids
#         return res
#
#     def init(self):
#         self._cr.execute("""
#             update cncw_account set parent_left=0 where parent_left is null;
#             update cncw_account set parent_right=0 where parent_left is null;
#         """)
#
#     def write(self, vals, ):
#         if 'active' in vals:
#             vals.update(dict(deprecated=vals.get('active', False)))
#         res = super(AccountAccount, self).write(vals)
#         return res
#
#     @api.onchange('name')
#     def onchange_name(self):
#         if self.name:
#             self.short_code = public.multi_get_letter(self, self.name)
#         else:
#             self.short_code = ''
#
#     @api.depends('dc_type')
#     def compute_dc_type(self):
#         for record in self:
#             if record.dc_type == 'D':
#                 record.dc_type_int = 1
#             else:
#                 record.dc_type_int = -1
